<?php

namespace App\Admin\Forms;

use Dcat\Admin\Widgets\Form;
use App\Models\ShortUrlApi;
use Dcat\Admin\Admin;
use App\Models\Domain;
use App\Models\ShortUrl;
use App\Services\ShortUrlService;

class CreateShortUrlForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $agent_id = Admin::user()->id;
        $out_video =  $input['out_video'] ?? null;

        //获取主域名
        $domain = Domain::show()->enter()->inRandomOrder()->first();
        if(!boolval($domain)){
            return $this->response()->alert(true)->error('生成错误')->detail('请稍后重试');
        }
        //原链接
        $code = createCode($agent_id,'-');
        $url="http://{$domain->domain}?code={$code}";
        //调用接口生成短链
        $api_service = new ShortUrlService();
        $res = $api_service->create($code,$domain->domain);
        if($res['code']!=1){
            return $this->response()->alert(true)->error('生成错误')->detail($res['msg']);
        }
        $short = $res['short'];
        //创建记录
        $create_res = ShortUrl::create([
            'agent_id'=>$agent_id,
            'link'=>$short,
            'url'=>$res['long'],
            'key'=>$code,
            'out_video'=>$out_video,
            'state'=>1
        ]);
        if($create_res){
            return $this->response()->alert(true)->success($short)->detail('推广链接已生成')->refresh();
        }
        else{
            return $this->response()->alert(true)->error('生成错误')->detail('请稍后重试');
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('out_video','盒子外链')->help('留空则首页没有播放器，可以当总链接使用');
    }
}
